// pages/order/index/index.js
import SessionUtil, {
    JxbHttpClient
} from '../../../data/session/session'
let pageSize = 15;
const Common = require('../../../utils/common.js');

Page({
    data: {
        token: '',
        userId: 0,
        SearchKey: '',
        types: '',
        typezt: '全部订单状态',
        topul: false,
        afters: false,
        tabNum0: true,
        tabNum2: false,
        tabNum3: false,
        tabNum4: false,
        tabNum1: false,
        orderList: [],
        statistics: {},
        pageNo: 1,
        isloading: true,
        nomore: false,
        moretext: "加载更多",
    },
    onLoad: function (options) {
        SessionUtil.getInstance().then(session => {
            wx.removeStorageSync('tagValue');
            wx.removeStorageSync('specialString');
            let userId = options.userId ? options.userId : '';
            this.setData({
                token: session.token,
                userId: userId
            });
            wx.setNavigationBarTitle({
                title: '订单列表'
            })
            if (options.fromMy) {
                this.type(options.fromMy);
            }
        })
    },
    onShow() {
        getApp().getSaleMode()
    },
    orderLists: function (action) {
        var page = this;
        var token = page.data.token,
            pageNo = page.data.pageNo,
            name = page.data.SearchKey,
            Types = page.data.types,
            userId = page.data.userId,
            nowData = page.data.orderList,
            statistics = {};

        if (pageNo < 0) {
            return;
        }
        page.setData({
            isloading: false,
            nomore: true
        });

        wx.showLoading();
        (new JxbHttpClient()).get({
            url: '/AppMaster/PosOrder/orderList',
            data: {
                pageSize: pageSize,
                pageNo: pageNo,
                name: name,
                type: Types,
                userId: userId,
            }
        }).then(jxbResp => {
            // 关闭加载
            wx.hideLoading();
            let order = jxbResp.data;
            let orderLists = this.tj(order);
            if (action === 'Page') {
                console.log('is Page!');
                if (order.length && order.length > 0) {
                    let newData = nowData.concat(orderLists);
                    this.setData({
                        orderList: newData,
                        pageNo: pageNo + 1,
                        isloading: true,
                        nomore: false,
                        moretext: "加载更多"
                    });
                    if (order.length < 10) {
                        this.setData({
                            isloading: true,
                            nomore: false,
                            moretext: "没有更多了"
                        })
                    }
                } else {
                    this.setData({
                        pageNo: -99,
                        isloading: true,
                        nomore: false,
                        moretext: "暂无数据"
                    });
                }
                return false;
            }
            if (action === 'Refresh') {
                console.log('is Refresh!');
                wx.stopPullDownRefresh();
                if (order.length > 0) {
                    this.setData({
                        orderList: orderLists,
                        pageNo: 1,
                        isloading: true,
                        nomore: false,
                        moretext: "加载更多"
                    })
                    if (order.length < 10) {
                        this.setData({
                            isloading: true,
                            nomore: false,
                            moretext: "没有更多了"
                        })
                    }
                } else {
                    this.setData({
                        orderList: '',
                        pageNo: 1,
                        isloading: true,
                        nomore: false,
                        moretext: "暂无数据"
                    });
                }
            }
        }).catch(err => {
            console.log(err)
            wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
            })
        })
    },
    changeType(e) {
        var id = e.currentTarget.id;
        this.type(id);
    },
    type: function (id) {
        var page = this;
        page.setData({
            orderList: {},
            pageNo: 1,
            types: id,
            tabNum1: false,
            tabNum2: false,
            tabNum3: false,
            tabNum4: false,
            tabNum0: false,
        })
        if (id == 0) {
            page.setData({
                typezt: '全部订单',
                tabNum0: true,
                types: '',
            })
        } else if (id == 1) {
            page.setData({
                typezt: '待付款',
                tabNum1: true,
            })
        } else if (id == 2) {
            page.setData({
                typezt: '待发货',
                tabNum2: true,
            })
        } else if (id == 3) {
            page.setData({
                typezt: '待收货',
                tabNum3: true,
            })
        } else if (id == 4) {
            page.setData({
                typezt: '交易完成',
                tabNum4: true,
            })
        }
        page.shady();
        page.orderLists('Refresh');
    },

    Topuls: function () {
        var page = this;
        if (page.data.topul) {
            page.shady();
        } else {
            page.setData({
                topul: true,
                afters: true,
            })
        }
    },
    shady: function () {
        //点击黑幕关闭
        this.setData({
            topul: false,
            afters: false,
        })
    },
    // 更新搜索关键词
    updateSearchKey: function (e) {
        this.setData({
            SearchKey: e.detail.value,
        })
    },
    goSearch: function () {
        var page = this;
        page.shady();
        var KEY = page.data.SearchKey;
        if (KEY) {
            page.setData({
                orderList: {},
                pageNo: 1,
            })
            page.orderLists('Refresh');
        } else {
            console.log('请输入用户名称！');
            Common.Alert('搜索提示', '请输入用户名称！');
        }
    },
    onPullDownRefresh: function () {
        var page = this;
        page.setData({
            orderList: {},
            pageNo: 1
        });
        page.orderLists('Refresh');
    },
    onReachBottom: function () {
        var page = this;
        var pageNo = page.data.pageNo;
        pageNo++
        page.setData({
            pageNo: pageNo
        });
        page.orderLists('Page');
    },
    tj: function (a) {
        // console.log(a);
        for (var i = 0; i < a.length; i++) {
            var quantity = 0;
            var itemids = [];
            var limits = [];
            for (var z = 0; z < a[i].activity_list.length; z++) {
                if (a[i].activity_list[z].activity_category == 6) {
                    itemids = itemids.concat(a[i].activity_list[z].item_ids);
                }
                if (a[i].activity_list[z].activity_category == 4) {
                    limits = limits.concat(a[i].activity_list[z].item_ids);
                }
            }
            for (var j = 0; j < a[i].item_list.length; j++) {
                quantity += parseInt(a[i].item_list[j].quantity);
                var z = Common.contains(itemids, a[i].item_list[j].item_id),
                    w = Common.contains(limits, a[i].item_list[j].item_id)
                if (z && w) {
                    a[i].item_list[j].activity_list = ['秒杀', '限购']
                } else {
                    if (z) {
                        a[i].item_list[j].activity_list = ['秒杀'];
                    }
                    if (w) {
                        a[i].item_list[j].activity_list = ['限购'];
                    }
                }
            }
            a[i].quantity = quantity
        }
        return a;
    },
    goDetail: function (e) {
        var itemId = e.currentTarget.id;
        wx.navigateTo({
            url: '/pages/order/orderDetail/orderDetail?itemId=' + itemId
        })
    },
    cancel: function (e) {
        var pags = this,
            order = e.currentTarget.id.split('-')
        wx.showModal({
            title: '提示',
            content: '确认取消订单吗？',
            cancelText: '我再想想',
            cancelColor: '#888',
            success: function (res) {
                if (res.confirm) {
                    pags.cancels(order)
                    console.log('用户点击确定')
                } else if (res.cancel) {}
            }
        })
    },
    deleted: function (e) {
        var pags = this,
            order = e.currentTarget.id.split('-')
        wx.showModal({
            title: '提示',
            content: '确认删除订单吗？',
            cancelText: '我再想想',
            cancelColor: '#888',
            success: function (res) {
                if (res.confirm) {
                    pags.deletes(order)
                    console.log('用户点击确定')
                } else if (res.cancel) {}
            }
        })
    },
    deletes: function (order) {
        (new JxbHttpClient()).post({
            url: '/AppMaster/PosOrder/delete',
            data: {
                orders_id: order[0],
                account_id: order[1],
            }
        }).then(jxbResp => {
            wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
            });
            this.setData({
                pageNo: 1
            });
            this.orderLists('Refresh');
        }).catch(err => {
            console.log(err)
            wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
            })
        })
    },
    cancels: function (order) {
        (new JxbHttpClient()).post({
            url: '/AppMaster/PosOrder/orderCanel',
            data: {
                orders_id: order[0],
                account_id: order[1],
            }
        }).then(jxbResp => {
            wx.showToast({
                title: '取消成功',
                icon: 'success',
                duration: 2000
            });
            this.setData({
                pageNo: 1
            });
            this.orderLists('Refresh');
        }).catch(err => {
            console.log(err)
            wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
            })
        })
    },
    complete: function (e) {
        let order = e.currentTarget.id.split('-');
        (new JxbHttpClient()).post({
            url: '/AppMaster/PosOrder/setOrderFinished',
            data: {
                orders_id: order[0],
                account_id: order[1],
            }
        }).then(jxbResp => {
            wx.showToast({
                title: jxbResp.message,
                icon: 'success',
                duration: 2000
            });
        }).catch(err => {
            console.log(err)
            wx.showToast({
                title: err.message,
                icon: 'none',
                duration: 2000
            })
        })
        this.setData({
            pageNo: 1
        });
        this.orderLists('Refresh');
    },
    payment: function (e) {
        var order = e.currentTarget.id.split('-');
        wx.navigateTo({
            url: '/pages/order/pay/pay?orderno=' + order[0] + "&paymoney=" + order[1] + '&orders_id=' + order[2]
        })
    }
})